import React from "react";
import View from "../base/View";
import defaultData from "./data";
import _ from 'lodash';
import { WeaBrowser, WeaLocaleProvider } from "ecCom";
import { inject, observer } from "mobx-react";
import fillin from '../../../../../apis/fillin';
import './index.less';
import { selectType, modeTypes } from '../../../../../constants/form';

const { DESIGN } = modeTypes;
const { CURRENT } = selectType;
const getLabel = WeaLocaleProvider.getLabel;
let curMember = {};

@inject('routing')
export default class SingleBrowserView extends View {
  constructor(props) {
    super(props);

    this.state = {
      member: {}
    }
  }

  componentDidMount() {
    const { data: { type, defaultValue }, modeType, value, uuid } = this.props;
    if (window.fromRouter === 'repair') {
      curMember = {};
    }

    if (modeType !== DESIGN && type === CURRENT) {
      fillin.getCurrUser().then(res => {
        this.setState({ member: { id: res.id, name: res.name  } })
        this.handleValueChange(res.id);

        if (defaultValue) {
          this.setState({ member: defaultValue });
          !value && this.handleValueChange(defaultValue.id);
        }

        if(value === null) {
          this.setState({ member: {} });
          this.handleValueChange(null);
        }

        if (_.isObject(value)) {
          this.setState({ member: { id: value.id, name: value.name } })
          this.handleValueChange(value.id);
        }

        if (curMember[uuid] && window.fromRouter !== 'repair') {
          this.setState({ member: curMember[uuid] || {} });
        }
      })
    }else {
      if (defaultValue) {
        this.setState({ member: defaultValue });
        !value && this.handleValueChange(defaultValue.id);
      }

      if(value === null) {
        this.setState({ member: {} });
        this.handleValueChange(null);
      }

      if (_.isObject(value)) {
        this.setState({ member: { id: value.id, name: value.name } })
        this.handleValueChange(value.id);
      }

      if (_.isString(value) && curMember[uuid] && window.fromRouter !== 'repair') {
        this.setState({ member: curMember[uuid] || {} });
      }
    }
  }

  receiveMessageFromIndex = (event) => {
    const { uuid, routing, shortkey } = this.props;

    if (event != undefined && event.data[uuid]) {
      const { ids, names } = event.data[uuid];

      if (ids) {
        if (names) {
          this.setState({ member: { id: ids, name: names } });
          curMember[uuid] = { id: ids, name: names };
          this.handleValueChange(ids);
          // this.props.routing.history.go(-1);
          routing.history.push({//本地开发模式需改成/edc/formview/${shortkey}
            pathname: `/`
          })
        }
      } else {
        this.setState({ member: {} });
        curMember[uuid] = {};
        this.handleValueChange('');
        // this.props.routing.history.go(-1);
        routing.history.push({//本地开发模式需改成/edc/formview/${shortkey}
          pathname: `/`
        })
      }

      window.removeEventListener("message", this.receiveMessageFromIndex, false);
    }
  }

  onBrowserChange = (ids, names) => {
    if (ids) {
      this.setState({ member: { id: ids, name: names } });
      this.handleValueChange(ids);
    } else {
      this.setState({ member: {} });
      this.handleValueChange('');
    }
  }

  componentWillReceiveProps (nextProps) {
    const { data: { defaultValue }, value } = nextProps;
    const { modeType } = this.props;
    
    modeType === DESIGN && this.setState({ member: defaultValue })
    if (modeType !== DESIGN && _.isObject(value)) {
      this.setState({ member: { id: value.id, name: value.name } })
      this.handleValueChange(value.id);
    }
  }

  renderForPC(data, value) {
    const { member } = this.state;
    
    return (
      <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@tc830i`}
        title={getLabel('513623', '人力资源')}
        type={1}
        textDecoration={true}
        replaceDatas={[member]}
        isSingle={true}
        onChange={(ids, names, datas) => this.onBrowserChange(ids, names)}
      />
    );
  }

  onBrowerHrmClick = () => {
    const { member } = this.state;
    const { uuid } = this.props;
    const finalValue = member ? encodeURI(JSON.stringify([member])) : '';

    //监听message事件
    window.addEventListener("message", this.receiveMessageFromIndex, false);
    window.fromRouter = 'browser';
    this.props.routing.history.push({
      pathname: 'edc/browserHrm',
      state: {
        finalValue, uuid,
        isSingle: '1'
      }
    });    
  }

  renderForMobile(data, value) {
    const { member } = this.state;

    return (//<a target='_blank' href={'/spa/hrm/static4mobile/index.html#/resourceInfo/' + value && value.id}>{value && value.name}</a>
      <div>
        <div className='mobile-browserHrm'>
          <div className='content'>
            <ul>
              <li>
                <span>{member.name}</span>
              </li>
            </ul>
          </div>
          <i onClick={this.onBrowerHrmClick} className='anticon anticon-search' />
        </div>
      </div>
    );
  }
  renderForReadonly(data, value) {
    const { member } = this.state;

    return (
      <div className='mobile-browserHrm'>
        <div className='content'>
          <ul>
            <li>
              <span>{member.name}</span>
            </li>
          </ul>
        </div>
      </div>
    );
  }
}

SingleBrowserView.defaultProps = {
  data: defaultData,
  value: ''
};